package com.binhthuan.catechist.client.data;

import com.binhthuan.catechist.shared.constant.Parameter;
import com.binhthuan.catechist.shared.constant.Service;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.FieldValueExtractor;
import com.smartgwt.client.data.XMLTools;
import com.smartgwt.client.data.fields.DataSourceDateField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.widgets.form.fields.SelectItem;

public class DateDS extends AbstractDS {

    private static DateDS instance;

    private DateDS() {
        super(Service.DATE);

        DataSourceIntegerField id = new DataSourceIntegerField(Parameter.ID);
        id.setHidden(true);
        id.setPrimaryKey(true);

        DataSourceDateField date = new DataSourceDateField(Parameter.DATE_OF_YEAR);
        date.setRequired(true);

        DataSourceTextField liturgicalDate = new DataSourceTextField(Parameter.LITURGICAL_DATE);

        DataSourceTextField description = new DataSourceTextField(Parameter.DESCRIPTION);
        description.setHidden(true);
        description.setFieldValueExtractor(new FieldValueExtractor() {

            @Override
            public Object execute(Object record, Object value, DataSourceField field, String fieldName) {
                String date = XMLTools.selectObjects(record, Parameter.DATE_OF_YEAR).getJavaScriptObject().toString();
                String detail = XMLTools.selectObjects(record, Parameter.LITURGICAL_DATE).getJavaScriptObject().toString();
                return convertToShortDateFormat(date) + " : " + detail;
            }
        });

        SelectItem yearEditor = new SelectItem(Parameter.YEAR);
        yearEditor.setRequired(true);
        yearEditor.setValueField(Parameter.ID);
        yearEditor.setDisplayField(Parameter.DESCRIPTION);
        yearEditor.setOptionDataSource(YearDS.getInstance());
        yearEditor.setWidth(250);
        yearEditor.setDefaultToFirstOption(true);

        DataSourceTextField year = new DataSourceTextField(Parameter.YEAR);
        year.setValueXPath(combineXPath(Parameter.YEAR, Parameter.ID));
        year.setTypeAsDataSource(YearDS.getInstance());
        year.setEditorType(yearEditor);

        setFields(id, date, liturgicalDate, description, year);
    }

    public static DateDS getInstance() {
        if (instance == null) {
            instance = new DateDS();
        }

        return instance;
    }
}
